﻿using System;
using System.Threading;

namespace ebc.minibus
{
    internal class SyncCtxSwitch
    {
        private readonly SynchronizationContext ctx;

        public SyncCtxSwitch()
        {
            this.ctx = SynchronizationContext.Current;
        }

        public Action<T> CreateHandler<T>(Action<T> handler)
        {
            return _ => this.ctx.Send(x => handler(_), null);
        }

        public Func<T, U> CreateHandler<T, U>(Func<T, U> handler)
        {
            return _ => {
                            var result = default(U);
                            this.ctx.Send(x => result = handler(_), null);
                            return result;
                        };
        }

        public Action CreateHandler(Action handler)
        {
            return () => this.ctx.Send(x => handler(), null);
        }
    }
}
